//
//  PhotoBrowserViewController.swift
//  WKweiBo
//
//  Created by 阿拉斯加的狗 on 15/12/20.
//  Copyright © 2015年 阿拉斯加的🐶. All rights reserved.
//

import UIKit
import SVProgressHUD
/// 可重用 Cell 标示符号
private let PhotoBrowserViewCellId = "PhotoBrowserViewCellId"

class PhotoBrowserViewController: UIViewController {

    //定义数组跟索引
    private var urls: [NSURL]
    private var currentIndexPath: NSIndexPath
    
    //MARK: - 监听方法
    @objc private func close() {
    
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func save() {
    
        //拿到图片
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        
        guard let image = cell.imageView.image else {
        
            return
        }
        
        //保存图片
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
    }
    
    //保存方法
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    
    @objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?) {
    
        //提示用户保存成功
        let message = (error == nil) ? "保存成功" : "保存失败"
        
        SVProgressHUD.showInfoWithStatus(message)
    
    }
    
    
    init(urls: [NSURL], indexPath: NSIndexPath) {
    
        self.urls = urls
        
        self.currentIndexPath = indexPath
        
        super.init(nibName: nil, bundle: nil)
    
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    override func loadView() {
        
        //设置根视图
        var rect = UIScreen.mainScreen().bounds
        
        rect.size.width += 20
        
        view = UIView(frame: rect)
        
//        view.backgroundColor = UIColor.blackColor()
        //更新UI
        setUpUI()
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        print(urls)
        print(currentIndexPath)
        
        //滚动到指定的位置
        collectionView.scrollToItemAtIndexPath(currentIndexPath, atScrollPosition: .CenteredHorizontally, animated: true)
    }

/// 懒加载控件
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserViewLayout())

    //关闭按钮
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())
    //保存按钮
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, color: UIColor.whiteColor(), imageName: nil, backColor: UIColor.darkGrayColor())
    
    //设置cell的流水布局
    private class PhotoBrowserViewLayout: UICollectionViewFlowLayout {
    
        private override func prepareLayout() {
            
            super.prepareLayout()
            itemSize = collectionView!.bounds.size
            minimumLineSpacing = 0
            minimumInteritemSpacing = 0
            scrollDirection = .Horizontal
            
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            collectionView?.pagingEnabled = true
      
        }
    
    }
    
    
}

/// 设置UI
private extension PhotoBrowserViewController {

    private func setUpUI() {
    
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        collectionView.frame = view.bounds
//        collectionView.backgroundColor = UIColor.redColor()
        
        //自动布局
        closeButton.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.left.equalTo(view.snp_left).offset(8)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        saveButton.snp_makeConstraints { (make) -> Void in
            
            make.bottom.equalTo(view.snp_bottom).offset(-8)
            make.right.equalTo(view.snp_right).offset(-28)
            make.size.equalTo(CGSize(width: 100, height: 36))
        }
        
        //监听方法
        closeButton.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        
        //准备控件
        prepareCollectionView()
    }

        //准备collectionView
    private func prepareCollectionView() {
    
        //注册可重用cell
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: PhotoBrowserViewCellId)
        
        //设置数据源
        collectionView.dataSource = self
    }
    
}


//数据源方法
extension PhotoBrowserViewController: UICollectionViewDataSource {

    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return urls.count
        
    }

    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PhotoBrowserViewCellId, forIndexPath: indexPath) as! PhotoBrowserCell
        
//        cell.backgroundColor = UIColor.blackColor()
        
        cell.photoDelegate = self
        
        cell.imageURL = urls[indexPath.item]
        
        return cell
        
    }
    
}

// MARK: - PhotoBrowserCellDelegate
extension PhotoBrowserViewController: PhotoBrowserCellDelegate {

    func photoBrowserCellDidTapImage() {
        close()
    }
    
    
    func photoBrowserCellDidZoom(scale: CGFloat) {
        
        let isHidden = (scale < 1)
        
        hideControls(isHidden)
        
        if isHidden {
            
            //进行缩放
            view.alpha = scale
            view.transform = CGAffineTransformMakeScale(scale, scale)
            
        }else {
            view.alpha = 1.0
            view.transform = CGAffineTransformIdentity
        
        }
    }
    
    
    //隐藏或者显示控件
    private func hideControls(isHidden: Bool) {
    
        closeButton.hidden = isHidden
        saveButton.hidden = isHidden
        
        collectionView.backgroundColor = isHidden ? UIColor.clearColor() : UIColor.blackColor()
    
    }
    
}

/// MARK: - PhotoBrowserDismissDelegated
extension PhotoBrowserViewController: PhotoBrowserDismissDelegate {

    //移除图像
    func imageViewForDismiss() -> UIImageView {
        
        let iv = UIImageView()
        
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        
        //获取cell
        let cell = collectionView.visibleCells()[0] as! PhotoBrowserCell
        
        iv.image = cell.imageView.image
        
        iv.frame = cell.scrollView.convertRect(cell.imageView.frame, toCoordinateSpace: UIApplication.sharedApplication().keyWindow!)
        
        return iv
        
    }

    
    //返回图像索引
    func indexPathForDismiss() -> NSIndexPath {
        
        //获取索引
        return collectionView.indexPathsForVisibleItems()[0]
    }

}

